package com.csun.dsms.controller;

import com.csun.dsms.comment.base.enums.ErrorCodeEnum;
import com.csun.dsms.comment.base.exception.BusinessException;
import com.csun.dsms.comment.config.properties.CsunProperties;
import com.csun.dsms.comment.core.annotation.Authorization;
import com.csun.dsms.comment.core.annotation.CurrentUser;
import com.csun.dsms.comment.core.annotation.ValidateAnnotation;
import com.csun.dsms.comment.core.support.CsunMessageSource;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.model.domain.*;
import com.csun.dsms.model.dto.file.FileDto;
import com.csun.dsms.model.dto.healthReport.HealthReportDTO;
import com.csun.dsms.model.dto.poor.PoorQueryDto;
import com.csun.dsms.model.dto.record.FinishTaskDto;
import com.csun.dsms.model.dto.record.RecordPercentDto;
import com.csun.dsms.model.dto.record.RecordQueryDto;
import com.csun.dsms.model.enums.PoorStatusEnum;
import com.csun.dsms.model.enums.RoleCodeEnum;
import com.csun.dsms.model.vo.poor.PoorChangeVo;
import com.csun.dsms.model.vo.poor.PoorVo;
import com.csun.dsms.model.vo.record.RecordPercentVo;
import com.csun.dsms.model.vo.staff.StaffVo;
import com.csun.dsms.service.*;
import com.csun.dsms.utils.*;
import com.csun.dsms.validator.DsmsRecordBeginValidator;
import com.csun.dsms.validator.DsmsRecordFinishValidator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author chisj chisj@foxmail.com
 * @version 1.0.0
 * @date 2021-09-24 10:49
 * @description: 小程序拦截器
 */
@RestController
@RequestMapping("/app")
public class DsmsAppController {

    @Resource
    private CsunMessageSource csunMessageSource;
    @Resource
    private DsmsStaffService dsmsStaffService;
    @Resource
    private DsmsPoorService dsmsPoorService;
    @Resource
    private DsmsAreaService dsmsAreaService;
    @Resource
    private DsmsRecordService dsmsRecordService;
    @Resource
    private DsmsResourceService dsmsResourceService;
    @Resource
    private OSSManageUtil ossManageUtil;
    @Resource
    private CsunProperties csunProperties;
    @Resource
    private DsmsUnitService dsmsUnitService;
    @Resource
    private DsmsHealthReportService healthReportService;
    @Resource
    private DsmsFileService fileService;
    @Resource
    private DsmsFileResourceService fileResourceService;



    @Resource
    private DsmsPoorChangeService dsmsPoorChangeService;
    /**
     * 获取服务人员信息
     *
     * @param login the login user
     *
     * @return  the wrapper.
     */
    @Authorization
    @RequestMapping(method = RequestMethod.GET, value = "/user")
    public Wrapper user(@CurrentUser DsmsUser login) {

        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        StaffVo staffVo = dsmsStaffService.selectByUserId(login.getId());

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), staffVo);
    }

    /**
     * 查询特困人员列表 - 分页
     *
     * @param poorQueryDto the poor query dto
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/poor/queryListWithPage")
    public Wrapper queryPoorListWithPage(@CurrentUser DsmsUser login,
                                         @RequestBody PoorQueryDto poorQueryDto) {

        List<PoorVo> poorVoList = Lists.newArrayList();

        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        dsmsStaff = dsmsStaffService.selectOne(dsmsStaff);

        // 根据片区id查询所有单位id
        List<Long> unitIdList = dsmsAreaService.selectUnitIdListByAreaId(dsmsStaff.getAreaId());
        if (PublicUtil.isNotEmpty(unitIdList)) {
            poorQueryDto.setUnitIdList(unitIdList);
            poorQueryDto.setApply(1);   // 审核通过
            poorQueryDto.setStatus(PoorStatusEnum.ENABLE.getType());

            poorVoList = dsmsPoorService.queryListWithPage(poorQueryDto);

            // 查询服务进度
            String date = DateUtil.getNowMonth();
            List<Long> poorIdList = Lists.newArrayList();
            for (PoorVo pv : poorVoList) {
                poorIdList.add(pv.getId());
            }
            if (PublicUtil.isNotEmpty(poorIdList)) {
                RecordPercentDto recordPercentDto = new RecordPercentDto();
                recordPercentDto.setDate(date);
                recordPercentDto.setPoorIdList(poorIdList);
                List<RecordPercentVo> recordPercentVoList = dsmsRecordService.queryRecordPercent(recordPercentDto);
                if (PublicUtil.isNotEmpty(recordPercentVoList)) {
                    for (PoorVo pv : poorVoList) {
                        for (RecordPercentVo rpv : recordPercentVoList) {
                            if (pv.getId().equals(rpv.getPoorId())) {
                                pv.setPercent(rpv.getPercent());    // 更新服务进度
                            }
                        }
                    }
                }
            }
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), new PageInfo(poorVoList));
    }

    /**
     * 查询特困人员详情
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/poor/showById/{id}")
    public Wrapper showPoorById(@PathVariable Long id) {

        DsmsPoor dsmsPoor = dsmsPoorService.selectByKey(id);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), dsmsPoor);
    }

    /**
     * 查询特困人员详情
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/poor/showDetailById/{id}")
    public Wrapper showPoorDetailById(@PathVariable Long id) {

        PoorVo poorVo = dsmsPoorService.showPoorDetailById(id);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), poorVo);
    }

    /**
     * 查询特困人员定位 - 分页
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/poor/queryLocationList")
    public Wrapper queryPoorLocationList(@CurrentUser DsmsUser login) {

        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        dsmsStaff = dsmsStaffService.selectOne(dsmsStaff);

        List<PoorVo> poorVoList = Lists.newArrayList();

        // 根据片区id查询所有单位id
        List<Long> unitIdList = dsmsAreaService.selectUnitIdListByAreaId(dsmsStaff.getAreaId());
        if (PublicUtil.isNotEmpty(unitIdList)) {
            poorVoList = dsmsPoorService.queryPoorLocationList(unitIdList);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), new PageInfo(poorVoList));
    }

    /**
     * 修改特困人员信息
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/poor/edit")
    public Wrapper editPoor(@CurrentUser DsmsUser login,
                            @RequestBody DsmsPoor dsmsPoor) {

        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        Preconditions.checkArgument(PublicUtil.isNotEmpty(dsmsPoor.getId()),
                csunMessageSource.getMessage("poor.id.null", null));

        // 完善特困人员头像
        DsmsPoor record = new DsmsPoor();
        record.setUpdateInfo(login);
        record.setId(dsmsPoor.getId());
        record.setHeadPic(dsmsPoor.getHeadPic());

        Integer result = dsmsPoorService.update(record);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null), result);
        }

        // 更新服务记录的特困人员头像
        dsmsRecordService.updatePoorHeadPic(dsmsPoor.getId(), dsmsPoor.getHeadPic());

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 我的任务列表 - 分页
     *
     * @param recordQueryDto the record query dto
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/record/queryListWithPage")
    public Wrapper queryRecordListWithPage(@CurrentUser DsmsUser login,
                                           @RequestBody RecordQueryDto recordQueryDto) {

        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        dsmsStaff = dsmsStaffService.selectOne(dsmsStaff);

        List<DsmsRecord> dsmsRecordList = Lists.newArrayList();

        // 根据片区id查询所有单位id
        List<Long> unitIdList = dsmsAreaService.selectUnitIdListByAreaId(dsmsStaff.getAreaId());
        if (PublicUtil.isNotEmpty(unitIdList)) {
            // 根据片区id查询所有的特困人员id
            List<Long> poorIdList = dsmsPoorService.selectPoorIdListByUnitList(unitIdList);
            if (PublicUtil.isNotEmpty(poorIdList)) {

                //recordQueryDto.setStatus(1);   // 待办
                recordQueryDto.setPoorIdList(poorIdList);
                List<Integer> statusList = new ArrayList<>();
                statusList.add(1);// 待办
                statusList.add(5);//进行中
                recordQueryDto.setStatusList(statusList);
                dsmsRecordList = dsmsRecordService.queryListWithPage(recordQueryDto);
            }
        }


        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), new PageInfo(dsmsRecordList));
    }

    /**
     * 任务详情
     *
     * @param id the record id
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/record/showById/{id}")
    public Wrapper showRecordById(@PathVariable Long id) {

        DsmsRecord dsmsRecord = dsmsRecordService.selectByKey(id);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), dsmsRecord);
    }

    /**
     * 点击开始任务
      * @param finishTaskDto
     * @return null
     * @author HD
     * @date 2022/3/11 9:27
     */
    @Authorization
    @PostMapping("/record/startTask")
    public Wrapper startTask(@CurrentUser DsmsUser login,
                             @Validated(DsmsRecordBeginValidator.class) @RequestBody FinishTaskDto finishTaskDto,
                             BindingResult br){
        // 查询用户是否为服务人员
        StaffVo staffVo = dsmsStaffService.selectByUserId(login.getId());
        if (PublicUtil.isEmpty(staffVo)) {
            throw new BusinessException(ErrorCodeEnum.GB10051001);
        }
        //查询服务记录
        List<DsmsRecord> dsmsRecords = dsmsRecordService.selectByRecordIds(finishTaskDto.getIds());
        for (DsmsRecord record:dsmsRecords) {
            if(record.getStaffId()!=null && !record.getStaffId().equals(staffVo.getId())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                        .getMessage("operation.failed", null));
            }
        }

        /*DsmsRecord record = dsmsRecordService.selectByKey(finishTaskDto.getId());
        if(record.getStaffId()!=null && !record.getStaffId().equals(login.getId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null));
        }*/
        Integer result = dsmsRecordService.startTask(finishTaskDto, login);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null), result);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 任务进行中上传图片
     * @param finishTaskDto
     * @return null
     * @author HD
     * @date 2022/3/11 9:27
     */
    @Authorization
    @PostMapping("/record/ongoingTask")
    public Wrapper ongoingTask(@CurrentUser DsmsUser login,
                             @Validated(DsmsRecordBeginValidator.class) @RequestBody FinishTaskDto finishTaskDto,
                             BindingResult br){
        // 查询用户是否为服务人员
        StaffVo staffVo = dsmsStaffService.selectByUserId(login.getId());
        if (PublicUtil.isEmpty(staffVo)) {
            throw new BusinessException(ErrorCodeEnum.GB10051001);
        }
        //查询服务记录
        List<DsmsRecord> dsmsRecords = dsmsRecordService.selectByRecordIds(finishTaskDto.getIds());
        for (DsmsRecord record:dsmsRecords) {
            if(record.getStaffId()!=null && !record.getStaffId().equals(staffVo.getId())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                        .getMessage("operation.failed", null));
            }
        }

        /*DsmsRecord record = dsmsRecordService.selectByKey(finishTaskDto.getId());
        if(record.getStaffId()!=null && !record.getStaffId().equals(login.getId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null));
        }*/
        Integer result = dsmsRecordService.ongoingTask(finishTaskDto, login);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null), result);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 完成任务
     *
     * @param finishTaskDto the finish task dto
     *
     * @return the wrapper
     */
    @Authorization
    @ValidateAnnotation
    @PostMapping(value = "/record/finishTask")
    public Wrapper finishTask(@CurrentUser DsmsUser login,
                              @Validated(DsmsRecordFinishValidator.class) @RequestBody FinishTaskDto finishTaskDto,
                              BindingResult br) {
        // 查询用户是否为服务人员
        StaffVo staffVo = dsmsStaffService.selectByUserId(login.getId());
        if (PublicUtil.isEmpty(staffVo)) {
            throw new BusinessException(ErrorCodeEnum.GB10051001);
        }
        //查询服务记录
        List<DsmsRecord> dsmsRecords = dsmsRecordService.selectByRecordIds(finishTaskDto.getIds());
        for (DsmsRecord record:dsmsRecords) {
            if(record.getStaffId()!=null && !record.getStaffId().equals(login.getId())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                        .getMessage("operation.failed", null));
            }
        }

        /*DsmsRecord record = dsmsRecordService.selectByKey(finishTaskDto.getId());
        if(record.getStaffId()!=null && !record.getStaffId().equals(login.getId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null));
        }*/
        Integer result = dsmsRecordService.finishTask(finishTaskDto, login);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null), result);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 服务记录列表 - 分页
     *
     * @param recordQueryDto the record query dto
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/record/queryHisListWithPage")
    public Wrapper queryRecordHisListWithPage(@CurrentUser DsmsUser login,
                                              @RequestBody RecordQueryDto recordQueryDto) {
        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        dsmsStaff = dsmsStaffService.selectOne(dsmsStaff);

        List<DsmsRecord> dsmsRecordList = Lists.newArrayList();

        // 根据片区id查询所有单位id
        List<Long> unitIdList = dsmsAreaService.selectUnitIdListByAreaId(dsmsStaff.getAreaId());
        if (PublicUtil.isNotEmpty(unitIdList)) {
            // 根据片区id查询所有的特困人员id
            List<Long> poorIdList = dsmsPoorService.selectALLPoorIdListByUnitList(unitIdList);
            if (PublicUtil.isNotEmpty(poorIdList)) {
                //recordQueryDto.setStatus(1);   // 待办
                recordQueryDto.setPoorIdList(poorIdList);
            }
        }

        if(recordQueryDto.getStatus() == null && recordQueryDto.getIsComplete() == null){
            recordQueryDto.setStaffId(dsmsStaff.getId());
        }
        //recordQueryDto.setStatus(2);   // 审核通过
        //recordQueryDto.setStaffId(dsmsStaff.getId());
        if(recordQueryDto.getCompanyEvaluation() != null){
            recordQueryDto.setStaffId(dsmsStaff.getId());
        }
        if(recordQueryDto.getIsComplete() != null){
            if(recordQueryDto.getIsComplete() == 0){
                List<Integer> statusList = new ArrayList<>();
                statusList.add(1);
                statusList.add(3);
                statusList.add(4);
                recordQueryDto.setStatusList(statusList);
            }
            if(recordQueryDto.getIsComplete() == 1){
                List<Integer> statusList = new ArrayList<>();
                statusList.add(2);
                recordQueryDto.setStaffId(dsmsStaff.getId());
                recordQueryDto.setStatusList(statusList);
                recordQueryDto.setPoorIdList(null);
            }
        }
        dsmsRecordList = dsmsRecordService.queryListWithPage(recordQueryDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), new PageInfo(dsmsRecordList));
    }


    /**
     * 资源上传 -- 小程序
     */
    @Authorization
    @RequestMapping(value="/upload",method= RequestMethod.POST,produces="application/json")
    public Wrapper upload(@CurrentUser DsmsUser login, HttpServletResponse response,
                HttpServletRequest request) throws Throwable {

        /* 获取文件描述参数 */
        String remark = request.getParameter("remark");

        List<DsmsResource> resources = new ArrayList<DsmsResource>();

        /* 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）*/
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());

        /* 检查form中是否有enctype="multipart/form-data" */
        if(multipartResolver.isMultipart(request)) {
            /* 将request变成多部分request */
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;

            /* 获取multiRequest 中所有的文件名*/
            Iterator iter = multiRequest.getFileNames();
            String timedate  = DateUtil.getOrderNum();	// 时间戳,避免文件覆盖

            while(iter.hasNext()) {

                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if(file != null) {

                    /* 文件属性获取 */
                    SourceType sourceType = MimeTypeUtil.getSourceType(file.getContentType());

                    /* MultipartFile 转 File */
                    File f=File.createTempFile("tmp", null);
                    file.transferTo(f);
                    f.deleteOnExit();
                    /* OSS文件上传 */
                    ossManageUtil.uploadFile(f, file.getOriginalFilename(), file.getContentType(), sourceType
                            .getSourceTypePath() + "/" + timedate);
                    /* 保存上传的文件属性 */
                    DsmsResource r = new DsmsResource();
                    r.setResourceName(file.getOriginalFilename());
                    r.setResourcePath(csunProperties.getAliyun().getOss().getAccessUrl() + "/"
                            + sourceType.getSourceTypePath() + "/" + timedate + "/" + file.getOriginalFilename());
                    if (StringUtils.isNotBlank(remark)) {
                        r.setRemark(remark);
                    }
                    r.setResourceTypeId(Integer.parseInt(sourceType.getSourceTypeId()));
                    r.setUpdateInfo(login);
                    // 添加资源记录
                    dsmsResourceService.save(r);

                    resources.add(r);
                }
            }
        }

        return WrapMapper.ok(resources);
    }

    /**
     * 小程序添加零时任务
     * @param login
     * @param record
     * @return
     */
    @Authorization
    @PostMapping("/programAdd")
    public Wrapper addRecord (@CurrentUser DsmsUser login, @RequestBody DsmsRecord record){
        //根据特困人员id获取特困人员基本信息
        PoorVo dsmsPoor = dsmsPoorService.showById(record.getPoorId());
        //查询该服务人员所在网格
        DsmsArea dsmsArea = dsmsAreaService.selectById(login.getId());

        DsmsRecord dsmsRecord = new DsmsRecord();
        BeanUtils.copyProperties(record,dsmsRecord);
        dsmsRecord.setStaffId(login.getId());
        dsmsRecord.setStaffName(login.getUserName());
        dsmsRecord.setCompanyId(login.getUnitId());
        dsmsRecord.setCompanyName(login.getUnitName());
        dsmsRecord.setPoorName(dsmsPoor.getName());
        dsmsRecord.setPoorAge(dsmsPoor.getAge());
        dsmsRecord.setPoorHeadPic(dsmsPoor.getHeadPic());
        dsmsRecord.setAreaId(dsmsArea.getId());
        dsmsRecord.setAreaName(dsmsArea.getName());
        dsmsRecord.setServiceType(2);
        dsmsRecord.setAuditStatus(0);
        Integer result = dsmsRecordService.save(dsmsRecord);

        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null), result);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 根据单位查询特困人员
     * @param unitId
     * @return
     */
    @Authorization
    @PostMapping("/queryPoorByUnitId")
    public Wrapper queryPoorByUnitId(Long unitId){
        DsmsPoor dsmsPoor = new DsmsPoor();
        dsmsPoor.setUnitId(unitId);
        dsmsPoor.setIsChange("1");
        dsmsPoor.setStatus("ENABLE");
        dsmsPoor.setApply(1);
        List<DsmsPoor> select = dsmsPoorService.select(dsmsPoor);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), select);
    }

    /**
     * 根据片区查询单位
     * @param login
     * @return
     */
    @Authorization
    @PostMapping("/queryUnitByAreaId")
    public Wrapper queryUnitByAreaId(@CurrentUser DsmsUser login){
        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        List<DsmsStaff> select = dsmsStaffService.select(dsmsStaff);
        List<DsmsUnit> dsmsUnits = dsmsUnitService.queryUnitByAreaId(select.get(0).getAreaId());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), dsmsUnits);
    }

    /**
     * 取消服务记录
     * @param login
     * @param id
     * @return
     */
    @Authorization
    @PostMapping("/deleteById")
    public Wrapper deleteById(@CurrentUser DsmsUser login, Long id){
        //查询服务记录
        DsmsRecord record = dsmsRecordService.selectByKey(id);
        if(record.getStaffId() == null || !login.getId().equals(record.getStaffId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null));
        }
        Integer result = dsmsRecordService.deleteByKey(id);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 修改服务记录
     * @param login
     * @param dsmsRecord
     * @return
     */
    @Authorization
    @PostMapping("/updateById")
    public Wrapper updateById(@CurrentUser DsmsUser login, @RequestBody DsmsRecord dsmsRecord){
        //查询服务记录
        DsmsRecord record = dsmsRecordService.selectByKey(dsmsRecord.getId());
        if(record.getStaffId() == null || !login.getId().equals(record.getStaffId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null));
        }
        //根据特困人员id获取特困人员基本信息
        PoorVo dsmsPoor = dsmsPoorService.showById(dsmsRecord.getPoorId());
        //查询该服务人员所在网格
        DsmsArea dsmsArea = dsmsAreaService.selectById(login.getId());

        DsmsRecord re = new DsmsRecord();
        BeanUtils.copyProperties(dsmsRecord,re);
        re.setStaffId(login.getId());
        re.setStaffName(login.getUserName());
        re.setCompanyId(login.getUnitId());
        re.setCompanyName(login.getUnitName());
        re.setPoorName(dsmsPoor.getName());
        re.setPoorAge(dsmsPoor.getAge());
        re.setPoorHeadPic(dsmsPoor.getHeadPic());
        re.setAreaId(dsmsArea.getId());
        re.setAreaName(dsmsArea.getName());
        re.setAuditStatus(0);
        Integer result = dsmsRecordService.update(re);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
      *查询当前片区服务人员
     * @return null
     * @author HD
     * @date 2022/2/16 15:02
     */
    @Authorization
    @PostMapping("/selectStaffByArea")
    public Wrapper selectStaffByArea (@CurrentUser DsmsUser login){
        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        dsmsStaff = dsmsStaffService.selectOne(dsmsStaff);
        DsmsStaff ds = new DsmsStaff();
        ds.setAreaId(dsmsStaff.getAreaId());
        List<DsmsStaff> select = dsmsStaffService.selectStaffByArea(ds);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), select);
    }

    /**
     * 查询当前片区所有特困人员
     * @return null
     * @author HD
     * @date 2022/2/17 14:10
     */
    @Authorization
    @PostMapping("/selectPoorByArea")
    public Wrapper selectPoorByArea(@CurrentUser DsmsUser login){
        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        dsmsStaff = dsmsStaffService.selectOne(dsmsStaff);

        List<DsmsRecord> dsmsRecordList = Lists.newArrayList();

        // 根据片区id查询所有单位id
        List<Long> unitIdList = dsmsAreaService.selectUnitIdListByAreaId(dsmsStaff.getAreaId());
        if (PublicUtil.isNotEmpty(unitIdList)) {
            // 根据片区id查询所有的特困人员
            List<PoorVo> poorIdList = dsmsPoorService.selectPoorByUnitList(unitIdList);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                    .getMessage("operation.success", null), poorIdList);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null));
    }

    /**
     * 查询当前片区
     * @return null
     * @author HD
     * @date 2022/2/17 14:10
     */
    @Authorization
    @PostMapping("/selectAreaByStaff")
    public Wrapper selectAreaByStaff(@CurrentUser DsmsUser login){
        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        //查询当前服务人员所在片区
        dsmsStaff = dsmsStaffService.selectAreaByStaff(dsmsStaff);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null),dsmsStaff.getAreaName());
    }

    /**
     * 人员信息变动提交
     * @return null
     * @author HD
     * @date 2022/2/17 14:10
     */
    @Authorization
    @ValidateAnnotation
    @PostMapping("/changePoorInfo")
    public Wrapper changePoorInfo(@CurrentUser DsmsUser login,
                                  @Valid @RequestBody PoorChangeVo poorChangeVo,
                                  BindingResult br){
        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }
        DsmsPoor dsmsPoor = dsmsPoorService.selectByKey(poorChangeVo.getPoorId());
        poorChangeVo.setCreator(login.getUserName());
        poorChangeVo.setCreatorId(login.getId());
        poorChangeVo.setPoorName(dsmsPoor.getName());
        poorChangeVo.setIdCard(dsmsPoor.getIdCard());
        DsmsPoorChange poorChange = new DsmsPoorChange();
        BeanUtils.copyProperties(poorChangeVo,poorChange);
        Integer result = dsmsPoorChangeService.save(poorChange);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 查询待完成任务数
      * @param login
     * @return null
     * @author HD
     * @date 2022/2/18 19:37
     */
    @Authorization
    @PostMapping("/queryServiceByStaff")
    public Wrapper queryServiceByStaff(@CurrentUser DsmsUser login){
        if (!login.getRoleCode().equals(RoleCodeEnum.STAFF.getCode())) {
            throw new BusinessException(ErrorCodeEnum.GB10051007);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setUserId(login.getId());
        dsmsStaff = dsmsStaffService.selectOne(dsmsStaff);
        RecordQueryDto recordQueryDto = new RecordQueryDto();
        List<DsmsRecord> dsmsRecordList = Lists.newArrayList();
        Integer result = 0;
        // 根据片区id查询所有单位id
        List<Long> unitIdList = dsmsAreaService.selectUnitIdListByAreaId(dsmsStaff.getAreaId());
        if (PublicUtil.isNotEmpty(unitIdList)) {
            // 根据片区id查询所有的特困人员id
            List<Long> poorIdList = dsmsPoorService.selectPoorIdListByUnitList(unitIdList);
            if (PublicUtil.isNotEmpty(poorIdList)) {
                recordQueryDto.setStatus(1);   // 待办
                recordQueryDto.setPoorIdList(poorIdList);
                Date date = new Date();
                String s = DateUtil.getTodayDate();
                recordQueryDto.setServiceDate(s);
                result = dsmsRecordService.queryServices(recordQueryDto);
            }
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null),result);
    }


    @PostMapping(value = "/healthReportSave")
    public Wrapper save(@RequestBody HealthReportDTO healthReportDTO) {
        DsmsHealthReport healthReport = new DsmsHealthReport();
        healthReport.setPoorId(healthReportDTO.getPoorId());
        healthReport.setCreateTime(new Date());
        healthReport.setBloodPressure(healthReportDTO.getBloodPressure());
        healthReport.setBloodSugar(healthReportDTO.getBloodSugar());
        healthReport.setRemark(healthReportDTO.getRemark());
        healthReportService.save(healthReport);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, null);
    }

    @PostMapping(value = "/file/list")
    public Wrapper list(@RequestBody FileDto fileDto) {
        PageHelper.startPage(fileDto.getPageNum(), fileDto.getPageSize());
        Example example = new Example(DsmsFile.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", "1");
        if (fileDto.getTitle() != null && !"".equals(fileDto.getTitle())) {
            criteria.andLike("title", "%" + fileDto.getTitle() + "%");
        }
        example.orderBy("uploadTime").desc();
        List<DsmsFile> dsmsFiles = fileService.selectByExample(example);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "操作成功", new PageInfo(dsmsFiles));
    }

    @PostMapping(value = "/file/download")
    public Wrapper download(@RequestBody FileDto fileDto) {
        Example example = new Example(DsmsFileResource.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("fileId", fileDto.getId());
        List<DsmsFileResource> dsmsFileResources = fileResourceService.selectByExample(example);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "操作成功", dsmsFileResources);
    }



}
